const ResponseError = require('../../../helper/ResponseError')
const generateRandomHash = require('../../../helper/generateRandomHash')

const tableName = 'utility_token'
const $join = [
  {
    tableName: 'administrator',
    foreignKey: 'administrator_id',
    tableKey: 'id',
  },
  {
    tableName: 'merchant',
    foreignKey: 'merchant_id',
    tableKey: 'id',
  },
  {
    tableName: 'user',
    foreignKey: 'user_id',
    tableKey: 'id',
  },
]

const find = async (knex, params, accountId) => {
  const result = await knex.service.find(tableName, { ...params, $join })
  return result
}

const get = async (knex, id, params, accountId) => {
  const record = await knex.service.get(tableName, id, { ...params, $join })
  return record
}

const create = async (knex, params, accountId) => {
  const record = await knex.service.create(tableName, {
    ...params,
    token: generateRandomHash(),
  })
  return record
}

const update = async (knex, id, params, accountId) => {
  const updateParams = params
  delete updateParams.administrator
  delete updateParams.merchant
  delete updateParams.user
  const record = await knex.service.update(tableName, id, updateParams)
  return record
}

const remove = async (knex, id, accountId) => knex.service.remove(tableName, id)

module.exports = {
  find,
  get,
  create,
  update,
  remove,
}
